# -*- coding: utf-8 -*-
import logging
from common.cache import redis_cache
from common.utils import telegram
from common.utils.send_p import send_text_msg
from common.withdraw import db as trans_db

_LOGGER = logging.getLogger(__name__)

ALIPAY_ERRORCODE = {
    'EXCEED_LIMIT_SM_AMOUNT': u'单笔额度超限',
    'EXCEED_LIMIT_DM_AMOUNT': u'日累计额度超限',
    'EXCEED_LIMIT_MM_AMOUNT': u'月累计金额超限',
    'PAYCARD_UNABLE_PAYMENT': u'付款账户余额支付功能不可用',
    'PAYER_NOT_EXIST': u'付款账户不存在',
    'PAYCARD_STATUS_UNABLE': u'付款账号状态异常',
    'PAYER_NOT_RELNAME_CERTIFY': u'付款用户姓名或其它信息不一致',
    'PAYER_CERTIFY_CHECK_FAIL': u'付款方人行认证受限',
    'PAYER_USERINFO_STATUS_ERROR': u'付款方用户状态不正常',
    'PAYER_BALANCE_NOT_ENOUGH': u'付款方余额不足',
    'PAYER_USER_INFO_ERROR': u'付款用户姓名或其它信息不一致',
    'NO_ACCOUNT_PAYMENT_PERMISSION': u'没有该账户的支付权限',
    'PAYMENT_INFO_INCONSISTENCY': u'重复的支付请求与前次支付信息不一致',
    'PAYER_USERINFO_NOT_EXSIT': u'付款用户姓名或其它信息不一致',
    'CARD_BIN_ERROR': u'付款用户不存在',
    'PAYEE_CARD_INFO_ERROR': u'收款人银行账号不正确',
    'INST_PAY_UNABLE': u'资金流出能力不具备',
    'PAYER_ACC_OCUPIED': u'付款人登录账号存在多个重复账户，无法确认唯一',
    'SYSTEM_ERROR': u'系统异常',
    'UNKNOWN_ERROR': u'未知异常',
}

GROUP_ID = 4335


def notify_balance(payer):
    try:
        payer_no = payer['no']
        payer_name = payer['payer']
        current_status = redis_cache.get_withdraw_status(payer_no)
        if not current_status or 0 == int(current_status):
            send_text_msg(3, GROUP_ID, u'justpay兑换余额不足,{}{}'.format(
                payer_name, payer_no))
            _LOGGER.info('notify_balance succ')
            redis_cache.set_withdraw_status(payer_no, 1)
    except Exception as e:
        _LOGGER.exception('notify_balance errir, %s', e)


_CLOSE_CHANNEL_ERRORS = ['PAYER_BALANCE_NOT_ENOUGH', 'EXCEED_LIMIT_DM_AMOUNT', 'EXCEED_LIMIT_MM_AMOUNT',
                         'PAYCARD_UNABLE_PAYMENT', 'PAYER_USERINFO_STATUS_ERROR', 'PAYER_CERTIFY_CHECK_FAIL',
                         'PAYER_NOT_RELNAME_CERTIFY', 'PAYCARD_STATUS_UNABLE']

CHAT_ID_JUSTPAY_PRODUCT_OPERATE = -270087999  # justpay产品
CHAT_ID_LOKI_CHARGE_AND_OPERATE = -247298958  # Loki - 支付&运营对接
CHAT_ID_WITCH_CHARGE_AND_OPERATE = -220589678  # witch - 支付&运营对接
CHAT_ID_ITECH_GROUP = -282055903  # I Tech 支付组
CHAT_ID_TG_FINANCE_WARNING_GROUP = -1001331494801  # justpay机器人

MCH_TYPE = {
    6001015: {'name': u'幸运彩票', 'chat_ids': [CHAT_ID_TG_FINANCE_WARNING_GROUP]},
    6001000: {'name': u'万豪彩票', 'chat_ids': [CHAT_ID_TG_FINANCE_WARNING_GROUP]},
    6001018: {'name': u'D-AGENT', 'chat_ids': [CHAT_ID_TG_FINANCE_WARNING_GROUP]},
}


def handle(err_msg, mch_id, chosed_payer, order_id):
    _LOGGER.info('alipay_exception_handle err_msg : %s, mch_id: %s, channel_id: %s,order_id: %s',
                 err_msg, mch_id, chosed_payer['chn_id'], order_id)
    if err_msg in _CLOSE_CHANNEL_ERRORS:
        notify_balance(chosed_payer)
        trans_db.update_channel_status(chosed_payer['chn_id'], 0)
        trans_db.unbind_chn(order_id)
    if mch_id not in MCH_TYPE.keys():
        return
    if err_msg not in ALIPAY_ERRORCODE.keys():
        return
    channel_msg = u'下分通道：**{}**-**{}** \n错误码：'.format(chosed_payer['chn_id'], chosed_payer['payer'])
    order_msg = u'\n订单号：%s\n' % order_id
    msg = channel_msg + ALIPAY_ERRORCODE.get(err_msg, err_msg) + order_msg
    try:
        for chat_id in MCH_TYPE[mch_id]['chat_ids']:
            telegram.send_text_msg_tele(chat_id, msg)
    except Exception as e:
        _LOGGER.exception('send_to_telegram_exception.(%s)' % e)
